package com.baizhi.cmfzmanager.configuration;

import com.baizhi.cmfzmanager.realm.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShrioConfiguration {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        Map map=new HashMap();
        // 设置过滤规则 需要自己改
// anon 匿名可访问 不用登录就可以访问
// authc 认证后可访问 登录后可以访问
        map.put("/login.jsp", "anon");
        map.put("/login","anon");
        map.put("/regist.jsp","anon");
        map.put("/regist","anon");
// 代表所有的都需要认证
        map.put("/**", "authc");
        //不配置 默认跳转项目下/login.jsp
        //shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
// 2.设置SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        return shiroFilterFactoryBean;
    }


    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(MyRealm realmDemo){
        DefaultWebSecurityManager securityManager = new
                DefaultWebSecurityManager();
// 设置自定义的realm
        securityManager.setRealm(realmDemo);
        return securityManager;
    }

    @Bean
    public MyRealm getMyRealm(CredentialsMatcher credentialsMatcher){
        MyRealm realmDemo = new MyRealm();
// 加密处理 设置密码凭证器
        realmDemo.setCredentialsMatcher(credentialsMatcher);
        return realmDemo;
    }

    @Bean
    public CredentialsMatcher getCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new
                HashedCredentialsMatcher();
// 设置算法的名字
        credentialsMatcher.setHashAlgorithmName("md5");
// 设置散列次数
        credentialsMatcher.setHashIterations(1024);
        return credentialsMatcher;


    }
}
